package org.example.order.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import org.example.contract.domain.ContractProduct;
import org.example.contract.mapper.ContractProductMapper;
import org.example.warehouse.domain.OrderDetail;
import org.example.warehouse.mapper.OrderDetailMapper;
import org.example.warehouse.service.IOrderDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.example.order.mapper.OrderMapper;
import org.example.order.domain.Order;
import org.example.order.service.IOrderService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单Service业务层处理
 *
 * @author 小孟微信：xiaomengcode
 * @date 2024-04-12
 */
@Service
public class OrderServiceImpl implements IOrderService
{
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ContractProductMapper contractProductMapper;

    /**
     * 查询订单
     *
     * @param orderId 订单主键
     * @return 订单
     */
    @Override
    public Order selectOrderByOrderId(Long orderId)
    {
        return orderMapper.selectOrderByOrderId(orderId);
    }

    /**
     * 查询订单列表
     *
     * @param order 订单
     * @return 订单
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<Order> selectOrderList(Order order)
    {
        return orderMapper.selectOrderList(order);
    }

    /**
     * 新增订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    @Transactional
    public int insertOrder(Order order)
    {

        //Json转List 订单产品详情
        JSONArray objects = JSONUtil.parseArray(order.getParams().get("operationNum"));
        List<ContractProduct> listContractProduct = JSONUtil.toList(objects, ContractProduct.class);

        order.setCreateTime(DateUtils.getNowDate());
        order.setCreateBy(ShiroUtils.getUserId()+"");
        order.setTotalNum(listContractProduct.size());
        order.setTotalPrice(getTotalMoney(listContractProduct));
        int i=orderMapper.insertOrder(order);

        listContractProduct.forEach(cart -> {
            if(cart.getOperationNum()>0){
                //2、插入详情
                OrderDetail detail =new OrderDetail();
                detail.setContractId(order.getContractId());
                detail.setContractCode(order.getContractCode());
                detail.setOrderId(order.getOrderId());
                detail.setPrice(cart.getPrice());
                detail.setOrderDetailId(order.getOrderId());
                detail.setNum(cart.getOperationNum());
                detail.setRemainNum(cart.getOperationNum());
                detail.setProductId(cart.getProductId());
                detail.setSupplierId(order.getSupplierId());
                detail.setCreateTime(order.getCreateTime());
                detail.setCreateBy(order.getCreateBy());
                orderDetailMapper.insertOrderDetail(detail);

                //3、更新购物车（清单）
                Integer useNum=  cart.getUseNum()+cart.getOperationNum();//使用数量
                cart.setUseNum(useNum);
                Integer remainNum= cart.getRemainNum()-cart.getOperationNum();//剩余数量
                cart.setRemainNum(remainNum);
                cart.setCreateBy(null);
                contractProductMapper.updateContractProduct(cart);//更新

            }

        });
        return i;
    }

    /**
     * 销售产品总数量
     * @param listStore
     * @return
     */
    private BigDecimal getTotalMoney(List<ContractProduct> listStore){
        BigDecimal totalMoney=BigDecimal.valueOf(0L);
        if (StringUtils.isNotNull(listStore)) {
            for (ContractProduct store : listStore) {
                BigDecimal multMoney = store.getPrice().multiply(BigDecimal.valueOf(store.getOperationNum()));
                totalMoney =multMoney.add(totalMoney);
            }
        }
        return totalMoney;
    }


    /**
     * 修改订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int updateOrder(Order order)
    {
        return orderMapper.updateOrder(order);
    }

    /**
     * 批量删除订单
     *
     * @param orderIds 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderByOrderIds(String orderIds)
    {
        return orderMapper.deleteOrderByOrderIds(Convert.toStrArray(orderIds));
    }

    /**
     * 删除订单信息
     *
     * @param orderId 订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderByOrderId(Long orderId)
    {
        return orderMapper.deleteOrderByOrderId(orderId);
    }
}
